//{include file=".layers.js"}//
(function () {
    var core = ecui,
        ui = core.ui,
        util = core.util,
        dom = core.dom,
        isToucher = document.ontouchstart !== undefined,
        isPointer = !!window.PointerEvent, // 使用pointer事件序列，请一定在需要滚动的元素上加上touch-action:none
        iosVersion = /(iPhone|iPad).*?OS (\d+(_\d+)?)/i.test(navigator.userAgent) ? +(RegExp.$2.replace('_', '.')) : undefined,
        QQVersion = /QQLiveBrowser\/(\d+\.\d)/i.test(navigator.userAgent) ? +RegExp.$1 : undefined,
        isWeixin = !!navigator.userAgent.match(/AppleWebKit.*MicroMessenger.*/),
        isDingTalk = navigator.userAgent.indexOf('DingTalk') > -1,
        isLogin = false;
    var socket;
    window.mao = {
        /**
         * 初始化dialog控件。
         * @public
         *
         * @param {string|Element} container dialog控件容器
         * @param {string} targetName 模板名称
         * @param {object} options 成功回调函数
         *
         * @return {Control} dialog 控件
         */
        initDialog: function (container, targetName, options) {
            if (typeof container === 'string') {
                container = ecui.$(container);
            }
            ecui.dispose(container);
            container.innerHTML = ecui.esr.getEngine().render(targetName, options);
            ecui.init(container);
            return container.children[0].getControl();
        },
        ui: {},
        wx: {},
        info: {
            appid: 'wx2054bed22814a315', // secret = '77305888f781790605ca7f1fd2eceaf6'
            ddReady: false,
            wxReady: false,
            isWeixin: isWeixin,
            isDingTalk: isDingTalk,
            baseInfo: [],
            baseInfoMap: {},
             //{if $prev}//corpId: 'ding37cd20907031c0b8', // 钉钉企业id
            //{else}//
            corpId: 'ding226f6e86537da5d7f2c783f7214b6d69', // 钉钉企业id
            //{/if}//
            agentId: '2220659488',  // 钉钉应用id
            tabConfig: [
                { title: '首页', size: 42, name: 'index', route: '/home/index' },
                { title: '审批', size: 42, name: 'approval', route: '/home/approval' },
                { title: '账本', size: 42, name: 'bill', route: '/home/bill' },
                { title: '我的', size: 42, name: 'me', route: '/home/me' },
            ]
        },
        util: {
            addLoading: function () {
                dom.addClass(document.body, 'ui-loading');
            },
            removeLoading: function () {
                dom.removeClass(document.body, 'ui-loading');
            },
            /**
             * 移除并释放已打开的dialog控件，用于离开路由时调用
             * @public
             *
             */
            removeDialog: function () {
                var dialogContainer = ecui.$('dialogContainer');
                if (dialogContainer) {
                    ecui.dispose(dialogContainer);
                    dialogContainer.innerHTML = '';
                }
            },
            toFixed: function (num, pow) {
                if (!pow && pow !== 0) {
                    pow = 2;
                }
                var correct = Math.pow(10, pow);
                return Math.round(Number(num) * correct) / correct;
            },

            /**
             * 生成时间戳的随机数
             * @return {String} 
             */
            getTimeRandom: function () {
                return  Date.now() + '' + Math.round(Math.random() * 10000);
            },
            /**
             * 遍历树。
             * @public
             *
             * @param {object} tree 遍历的树
             * @param {function} fn 遍历子节点前执行函数
             * @param {function} _fn 遍历子节点后执行函数
             *
             * @return
             */
            mapTree: function (tree, fn, _fn) {
                fn(tree);
                (tree.children || []).forEach(function (item) {
                    mao.util.mapTree(item, fn, _fn);
                });
                if (_fn) {
                    _fn(tree);
                }
            },
            /**
             * 查询树节点
             * @public
             *
             * @param {object} tree 遍历的树
             * @param {string|number} id 查询的主键id
             * @param {string} key 指定要查询的key
             *
             * @return
             */
            findTree: function (tree, id, key) {
                if (!id) {
                    return [];
                }
                key = key || 'id';
                var arr = [];
                function mapTree (tree) {
                    if (id === tree[key]) {
                        arr.push(tree);
                        return true;
                    } else {
                        var children = tree.children || [];
                        for (var i = 0, item; item = children[i]; i++) {
                            if (mapTree(item)) {
                                arr.push(tree);
                                return true;
                            }
                        }
                    }
                }
                mapTree(tree);
                return arr.reverse();
            },
            findDept: function (deptId) {
                var dept = mao.util.findTree(mao.info.deptTree[0], deptId);
                dept = dept ? dept[0] || {} : {};
                return dept;
            },
            initSocket: function () {
                if (socket) {
                    socket.close();
                }
                socket = ecui.io.openSocket(
                    //{if $prev}//'ws.oa.bitauto.com/barrage-api/barrage',
                    //{else}//
                    't.yinyueapp.com/erp-management/ws/notice/' + mao.staffInfo.staffId,
                    //{/if}//
                    function (data) {
                        if (!(data instanceof Object)) {
                            return;
                        }
                        // type === 1 时是 消息数量
                        if (data.type === 1) {
                        // type === 2 时是签到人数信息
                            var navTab = ecui.get('navTab'),
                                approveListTab = ecui.get('approve-list-tab');
                            if (navTab) {
                                var count = dom.first(dom.first(navTab.getItem(0).getMain()));
                                if (data.content.newsCount) {
                                    count.innerHTML = data.content.newsCount > 99 ? '99+' : data.content.newsCount;
                                    dom.removeClass(count, 'ui-hide');
                                } else {
                                    count.innerHTML = '';
                                    dom.addClass(count, 'ui-hide');
                                }
                            }
                            if (approveListTab) {
                                dom.first(approveListTab.getItem(0).getBody()).innerHTML = '待我审批的(' + data.content.approvalCount + ')';
                            }
                        } else if (data.type === 2) {
                        // type === 3 节目流程
                        } else if (data.type === 3) {
                            // 设置当前正在进行节目
                        // type === 4 节目点赞数量
                        } else if (data.type === 4) {
                            // 设置点赞数量
                        }
                    }.bind(this),
                    function () {
                        this.tip('error');
                    }.bind(this),
                    {}
                );
            },

            getLayer: function (control) {
                for (; control = control.getParent(); ) {
                    if (control instanceof ecui.esr.AppLayer) {
                        break;
                    }
                }
                return control;
            },

            hasSubmitAgain: function (auditState) {
                auditState = +auditState;
                var res = false;
                if (auditState === 2 || auditState === 4 || auditState === 5) {
                    res = true;
                }
                return res;
            },

            parseData: function (data, value, key) {
                if (!data) {
                    return value;
                }
                key = key || 'id';
                return data.find(function (item) {
                    return item[key] == value;
                });
            },
            chooseImage: function (options) {
                if (mao.info.ddReady) {
                    dd.biz.util.chooseImage({
                        count: 1,
                        secret: false,
                        sourceType: options.sourceType || ['camera', 'album'],
                        position: 'back',
                        onSuccess: function(res) {
                            try {
                                mao.util.addLoading();
                                res.files.forEach(function (item) {
                                    mao.util.uploadFile(item.path, Object.assign({ fileName: item.path.split('/').pop() }, options));
                                });
                            } catch (err) {
                                console.log(err);
                                mao.util.removeLoading();
                            }
                        },
                        onFail: function(err) {
                            options.onFail(err);
                        }
                    });
                }
            },
            uploadFile: function (filePath, options) {
                console.log('filePath: ', filePath, options);
                dd.biz.util.uploadFile({
                    url: options.url || (location.origin + '/erp-management/file/upload'),
                    filePath: filePath,
                    fileName: 'file',
                    header: ecui.esr.headers,
                    onSuccess: function(res) {
                        options.onSuccess(res.data);
                    },
                    onFail: function(err) {
                        options.onFail(err);
                    }
                })
            },
            /**
             * 钉钉签名验证
             * @public
             *
             * @return 
             */ 
            ddSignature: function () {
                ecui.esr.request(
                    'ddsignature@GET /erp-management/dingding/jsapi-params?url=' + encodeURIComponent(location.origin + location.pathname),
                    function () {
                        var signature = ecui.esr.getData('ddsignature');
                        var code = ecui.esr.getData('ddsignature_CODE');
                        if (code === 0) {
                            mao.info.signature = signature;
                            dd.config({
                                agentId: signature.agentId, // 必填，微应用ID
                                corpId: signature.corpId,//必填，企业ID
                                timeStamp: signature.timeStamp, // 必填，生成签名的时间戳
                                nonceStr: signature.nonceStr, // 必填，自定义固定字符串。
                                signature: signature.signature, // 必填，签名
                                type: 0,   //选填。0表示微应用的jsapi,1表示服务窗的jsapi；不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
                                jsApiList : [
                                    'runtime.info',
                                    'biz.contact.choose',
                                    'device.notification.confirm',
                                    'device.notification.alert',
                                    'device.notification.prompt',
                                    'biz.ding.post',
                                    'biz.util.openLink',
                                    'biz.util.chooseImage', // 选择图片
                                    'biz.util.previewImage', // 预览图片
                                    'biz.util.uploadFile', // 上传文件
                                    'biz.util.downLoadFile' // 下载文件
                                ], // 必填，需要使用的jsapi列表，注意：不要带dd。
                                onSuccess: function(res) {
                                    console.log('config res', JSON.stringify(res))
                                },
                                onFail : function(err) {
                                    console.log('config err', JSON.stringify(err))
                                }
                            });

                        }
                    },
                    function (error) {
                        console.warn('获取签名失败');
                        return false;
                    }
                );
                dd.ready(function () {
                    mao.info.ddReady = true;
                    dom.addClass(document.body, 'dd');
                    console.log('钉钉 鉴权成功');
                });

                dd.error(function (err) {
                    console.log('钉钉 鉴权失败', err);
                });
            },

            /**
             * 钉钉登录
             * @public
             *
             * @return 
             */ 
            ddLogin: function () {
                function login (code) {
                    if (isLogin) {
                        return;
                    }
                    isLogin = true;
                    var url = 'data@GET /erp-management/dingding/user?code=' + code;
                    if (mao.info.userId) {
                        url = 'data@GET /erp-management/dingding/login?userId=' + mao.info.userId;
                    }
                    ecui.esr.request(
                        url,
                        function () {
                            isLogin = false;
                            var data = ecui.esr.getData('data');
                            var _code = ecui.esr.getData('data_CODE');
                            if (_code === 0) {
                                window.localStorage.setItem('openId', data.token);
                                dd.util.domainStorage.setItem({
                                    name: 'openId', // 存储信息的key值
                                    value: data.token, // 存储信息的key值
                                    onSuccess: function(info) {
                                    },
                                    onFail: function(err) {
                                        alert(JSON.stringify(err));
                                    }
                                });
                                if (!mao.info.userId) {
                                    window.localStorage.setItem('userId', data.userId);
                                    dd.util.domainStorage.setItem({
                                        name: 'userId', // 存储信息的key值
                                        value: data.userId, // 存储信息的key值
                                        onSuccess: function(info) {
                                        },
                                        onFail: function(err) {
                                            alert(JSON.stringify(err));
                                        }
                                    });
                                }
                                location.reload();
                            } else {
                                delete mao.info.userId;
                                dd.util.domainStorage.removeItem({ name:'userId' });
                                window.localStorage.removeItem('userId');
                            }
                        },
                        function (error) {
                            isLogin = false;
                            return false;
                        }
                    );
                }
                dd.ready(function () {
                    if (mao.info.userId) {
                        login();
                    } else {
                        dd.runtime.permission.requestAuthCode({
                            corpId: mao.info.corpId,
                            onSuccess: function(result) {
                                login(result.code);
                            },
                            onFail: function(err) {
                                console.log('requestAuthCode', err);
                                ecui.tip('warn', '请切换到您当前所在企业');
                            }
                        })
                    }
                });
            },

            /**
             * 微信签名验证
             * @public
             *
             * @return 
             */ 
            wxSignature: function () {
                ecui.esr.request(
                    'signature@JSON /erp-management/weixin/signature?url=' + encodeURIComponent(location.origin + location.pathname),
                    function () {
                        var signature = ecui.esr.getData('signature');
                        var code = ecui.esr.getData('signature_CODE');
                        if (code === 0) {
                            mao.wx.signature = signature;
                            wx.config({
                                // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                appId: mao.info.appid, // 必填，公众号的唯一标识
                                timestamp: signature.timestamp, // 必填，生成签名的时间戳
                                nonceStr: signature.noncestr, // 必填，生成签名的随机串
                                signature: signature.signature,// 必填，签名
                                jsApiList: [
                                    'previewImage', // 预览图片接口
                                    'chooseImage', // 拍照或从手机相册中选图接口
                                    'uploadImage', // 上传图片
                                    'getNetworkType', // 获取网络状态接口
                                    'scanQRCode', // 调起微信扫一扫接口
                                    'chooseWXPay' // 发起一个微信支付请求
                                ] // 必填，需要使用的JS接口列表
                            });
                            wx.ready(function () {
                                mao.info.wxReady = true;
                                dom.addClass(document.body, 'wx');
                                console.log('wx 鉴权成功');
                            });
                            wx.error(function (err) {
                                console.log('wx 鉴权失败');
                            });
                        }
                    },
                    function (xhr) {
                        console.warn('获取签名失败');
                    }
                );
            },

            setTitle: function (title) {
                if (mao.info.isDingTalk) {
                    dd.ready(function () {
                        dd.setNavigationTitle({
                            title: title,
                            success: function () {},
                            fail: function () {},
                            complete: function () {}
                        });
                    });
                } else {
                    window.document.title = title;
                }
            },

            /**
             * 根据基础字体大小 和 效果图宽度设置 根节点字体大小
             * @param baseFontSize 浏览器默认字体大小 [注]浏览器最小字体为12像素，所以该值必需大于等于12
             * @param baseWidth 设计稿的尺寸
             */
            clearSizeTimer: function () {},

            initFontSize: function(baseFontSize, baseWidth) {
                var clientWidth,
                    clientHeight = document.documentElement.clientHeight || window.innerHeight;
                // 获取当前屏幕宽度
                if (isToucher) {
                    clientWidth = document.documentElement.clientWidth || window.innerWidth;
                } else {
                    clientWidth = 375 / 750 * clientHeight;
                    mao.util.clearSizeTimer = util.timer(function () {
                        var body = document.body;
                        if (body) {
                            mao.util.clearSizeTimer();
                            body.style = 'margin: 0 auto !important;';
                            body.style.width = clientWidth + 'px';
                            body.style.height = clientHeight + 'px';
                            dom.addClass(body, 'pc');
                        }
                        // 在pc端展示h5页面时，调整 getView 方法的 client 固定为 body 来计算位置
                        util.getView = function () {
                            var body = document.body,
                                html = dom.parent(body),
                                client = body,
                                scrollTop = html.scrollTop + body.scrollTop,
                                scrollLeft = html.scrollLeft + body.scrollLeft,
                                clientWidth = client.clientWidth,
                                clientHeight = client.clientHeight;

                            return {
                                top: scrollTop,
                                right: scrollLeft + clientWidth,
                                bottom: scrollTop + clientHeight,
                                left: scrollLeft,
                                width: clientWidth,
                                height: clientHeight,
                                pageWidth: Math.max(html.scrollWidth, body.scrollWidth, clientWidth),
                                pageHeight: Math.max(html.scrollHeight, body.scrollHeight, clientHeight)
                            };
                        };
                    }, -10);
                }
                // 根据宽度计算根节点字体大小
                var size = clientWidth / baseWidth * baseFontSize;
                document.querySelector('html').style.fontSize = size + 'px';
            }
        }
    };
    // 设置h5与后端请求的token，一般登录成功后 存进了 本地浏览器或原生APPwebview的localStorage
    ecui.esr.headers = {
        'x-client': isDingTalk ? 'DingTalk' : (isWeixin ? 'WeChat' : 'h5'),
        'x-open-id': window.localStorage.getItem('openId'),
        'x-access-token': window.localStorage.getItem('openId')
    };
    ui.Upload.prototype._oHeaders = ecui.esr.headers;
    mao.info.userId = window.localStorage.getItem('userId');

    if (isDingTalk) {
        var now = Date.now();
        dd.ready(function () {
            dd.util.domainStorage.getItem({
                name: 'openId', // 存储信息的key值
                onSuccess : function(info) {
                    if (info.value) {
                        ecui.esr.headers['x-access-token'] = info.value;
                        ecui.esr.headers['x-open-id'] = info.value;
                    }
                    console.log('info: ', info, Date.now() - now);
                },
                onFail : function(err) {
                    // alert(JSON.stringify(err));
                }
            });
            dd.util.domainStorage.getItem({
                name: 'userId', // 存储信息的key值
                onSuccess : function(info) {
                    if (info.value) {
                        mao.info.userId = info.value;
                    }
                    console.log(info, Date.now() - now);
                },
                onFail : function(err) {
                    // alert(JSON.stringify(err));
                }
            });
        });
    }
    //{if !$prev}//
    mao.info.appid = 'wx0e1c69a45f2a6c5c'; // secret = '5bb03649bf848c4b398f1ef4e7ea69b9'
    //{/if}//

    // var redirect_uri = http://u.mao-livehouse.com/maolive-app/index.html#/venueOrder/calendar
    // 微信入口链接： https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2054bed22814a315&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect

    //统一对请求成功返回参数做分类
    var noTipCodes = [20001, 20002];
    ecui.esr.onparsedata = function (url, data) {
        if (data.data.pageNo !== undefined && data.data.total === undefined &&  data.data.offset === undefined) {
            data.data.total = data.data.totalRecord;
            data.data.offset = data.data.pageSize * (data.data.pageNo - 1);
        }
        var code = data.code;
        if (0 === code) {
            data = data.data;
            return data;
        }
        if (code === 12011) {
            var url = 'https://u.mao-livehouse.com/maolive-app/bind.html';
            //{if !$prev}//
            url = 'https://t.yinyueapp.com/maolive-app/bind.html';
            //{/if}//
            // 分支3.4：登录相关的错误
            wx.ready(function () {
                //{if 1}//window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + mao.info.appid + '&redirect_uri=' + url + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                //{/if}//
            });
            dd.ready(function () {
                mao.util.ddLogin();
            });
        } else {
            if (code === 300000) {
                throw data.msg;
            }
            if (noTipCodes.indexOf(code) < 0) {
                ecui.tip('warn', data.msg);
            }
        }
        return code;
    };
    var iosVersion = /(iPhone|iPad).+OS (\d+)/i.test(navigator.userAgent) ?  +(RegExp.$2) : undefined;
    var textReady = ecui.ui.Text.prototype.$ready;
    ecui.ui.Text.prototype.$ready = function () {
        textReady.call(this);
        this.getInput().setAttribute('autocomplete', 'off');
    };
    ecui.esr.onexception = function (e) {
        console.error(e);
        ecui.esr.setGlobal('noNetwork', true);
        ecui.tip('warn', '请检查您的网络连接');
    };
    function setRouteHeader (route) {
        var main = ecui.$(route.main);
        if (main) {
            var header = main.header;
            if (header) {
                var title = header.querySelector('.title-wrap').innerText.trim();
                mao.util.setTitle(title);
            }
        }
    }
    ecui.esr.onchange = function (route) {
        // console.log(route);
        setRouteHeader(route);
    };
    ecui.esr.oncached = function (route) {
        // console.log(route);
        setRouteHeader(route);
    };
    // 定义index单页应用下的全局对象，主要用来提供本项目的特有控件等
    // ecui.ui.MCalendar.prototype.getFormValue = function () {
    //     return this.getValue() ? new Date(this.getValue().replace(/-/g, '/')).pattern('yyyy-MM-dd HH:mm:ss') : '';
    // };
    // 解析场次
    window.actionCutting = function (actionCuttings) {
        return actionCuttings.map(function (item) { return item.name; }).join('、');
    };

    //初始化 字体100px , 设计稿宽640px
    mao.util.initFontSize(75, 750);
    // 窗口大小改变时设置根节点字体大小，通过字体大小来控制页面元素尺寸的缩放
    window.addEventListener('resize', mao.util.initFontSize);

    /**
     * 权限验证
     * @private
     * @example
     * <input ui="type:input-control;ext-permission:aa||bb"> 判断两个是否有其中一个，有任何一个则显示
     * <li class="person-city" ui="ext-permission:system:read;">
            <a href="#operation.city">区域管理</a>
       </li>
     **/
    ecui.ext.permission = {
        constructor: function (value) {
            // 权限列表
            var permCodes = mao.info.baseInfo.permission.permCodes;

            var array = value.split('||'),
                flag = false;
            array.forEach(function (item) {
                if (permCodes.indexOf(item) >= 0) {
                    flag = true;
                }
            });
            if (!flag) {
                this.hide();
            }
        }
    };

}());
